package cn.tedu.tmall.front.mall.service.impl;

import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.tmall.front.mall.converter.GoodsToCartConverter;
import cn.tedu.tmall.front.mall.dao.cache.ICartCacheRepository;
import cn.tedu.tmall.front.mall.dao.persist.repository.IGoodsRepository;
import cn.tedu.tmall.front.mall.pojo.po.CartPO;
import cn.tedu.tmall.front.mall.pojo.vo.CartListItemVO;
import cn.tedu.tmall.front.mall.pojo.vo.GoodsStandardVO;
import cn.tedu.tmall.front.mall.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
@Slf4j
public class CartService implements ICartService {
    @Autowired
    private ICartCacheRepository cartCacheRepository;
    @Autowired
    private IGoodsRepository goodsRepository;

    @Override
    public void addNew(CurrentPrincipal currentPrincipal, Long goodsId, Integer goodsNum) {
        log.debug("开始处理添加商品到购物车的业务");
        GoodsStandardVO goods = goodsRepository.getStandardById(goodsId);
        if (goods == null) {
            String message = "添加购物车失败,商品不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        if (goods.getIsPutOn() != 1) {
            String message = "添加购物车失败,商品已下架";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        CartPO cartPO = new CartPO(goodsId, goodsNum);
        CartPO carCache = cartCacheRepository.getByUserAndGoods(currentPrincipal.getId(), goodsId);
        if (carCache != null) {
            cartPO.setGoodsNum(carCache.getGoodsNum() + goodsNum);
        }
        cartCacheRepository.put(currentPrincipal.getId(), cartPO);
    }

    @Override
    public List<CartListItemVO> list(CurrentPrincipal currentPrincipal) {
        log.debug("开始处理查询购物车列表的业务");
        List<CartListItemVO> cartList = new ArrayList<>();
        // 从缓存中拿商品的id跟数量
        List<CartPO> cartPOList = cartCacheRepository.listByUser(currentPrincipal.getId());
        for (CartPO cartPO : cartPOList) {
            // 根据商品的id查询商品的全部信息
            GoodsStandardVO goods = goodsRepository.getStandardById(cartPO.getGoodsId());
            if (goods != null) {
                // 将查询到的数据转换为CartListItemVO类型
                CartListItemVO cartListItemVO = GoodsToCartConverter.convertToCart(cartPO, goods);
                cartList.add(cartListItemVO);
            }
        }
        return cartList;
    }

    @Override
    public Integer increaseNum(CurrentPrincipal currentPrincipal, Long goodsId) {
        log.debug("开始处理【将购物车中商品的数量增加1】的业务，当事人：{}，商品：{}", currentPrincipal, goodsId);
        return increaseNum(currentPrincipal.getId(),goodsId,1);
    }

    @Override
    public Integer reduceNum(CurrentPrincipal currentPrincipal, Long goodsId) {
        log.debug("开始处理【将购物车中商品的数量减少1】的业务，当事人：{}，商品：{}", currentPrincipal, goodsId);
        return reduceNum(currentPrincipal.getId(),goodsId,1);
    }

    @Override
    public void delete(CurrentPrincipal currentPrincipal, Long goodsId) {
        log.debug("开始处理删除购物车中的商品");
        cartCacheRepository.deleteByUserAndGoods(currentPrincipal.getId(), goodsId);

    }

    /**
     * 增加购物车中的商品的数量
     *
     * @param userId  用户ID
     * @param goodsId 商品ID
     * @param num     增加的商品的数量
     * @return 新的数量
     */
    private Integer increaseNum(Long userId, Long goodsId, Integer num) {
        checkGoodsState(goodsId);
        CartPO cartCache = cartCacheRepository.getByUserAndGoods(userId, goodsId);
        Integer newNum = cartCache.getGoodsNum() + num;
        CartPO cartPO = new CartPO(goodsId, newNum);
        cartCacheRepository.put(userId, cartPO);
        return newNum;
    }

    /**
     * 减少购物车中的商品的数量
     *
     * @param userId  用户ID
     * @param goodsId 商品ID
     * @param num     减少的商品的数量
     * @return 新的数量
     */
    private Integer reduceNum(Long userId, Long goodsId, Integer num) {
        checkGoodsState(goodsId);
        CartPO cartCache = cartCacheRepository.getByUserAndGoods(userId, goodsId);
        // 判断缓存中获取有该商品
        if (cartCache == null) {
            return 0;
        }

        Integer newNum = cartCache.getGoodsNum() - num;
        // 当用户的在购物车中商品的数量小于1时,删除数据
        if (newNum <= 0) {
            cartCacheRepository.deleteByUserAndGoods(userId, goodsId);
            return 0;
        }

        CartPO cartPO = new CartPO(userId, newNum);
        cartCacheRepository.put(userId, cartPO);
        return newNum;
    }

    private void checkGoodsState(Long goodsId) {
        GoodsStandardVO goods = goodsRepository.getStandardById(goodsId);

        // 判断商品是否存在
        if (goods == null) {
            String message = "操作失败,商品数量不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        // 判断商品是否为下架状态
        if (!goods.getIsPutOn().equals(PUT_ON_STATE_ON)) {
            String message = "操作失败,此商品已下架";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

    }
}
